package com.revenant.driver.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.AMapLocationQualityReport;
import com.apkfuns.logutils.LogUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.RomUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.revenant.driver.App;
import com.revenant.driver.R;
import com.revenant.driver.adapter.AlertInfoListAdapter;
import com.revenant.driver.adapter.NewMainAdapter;
import com.revenant.driver.base.BaseActivity;
import com.revenant.driver.base.SplashActivity;
import com.revenant.driver.bean.BaseBean.MessageEvent;
import com.revenant.driver.bean.DriverTrackBean;
import com.revenant.driver.bean.ShipperBean.PersonalDetailBean;
import com.revenant.driver.bean.TongJiListBean;
import com.revenant.driver.bean.UpdateBean;
import com.revenant.driver.ui.XieYiActivity;
import com.revenant.driver.ui.fragment.DriverLianWangFragment;
import com.revenant.driver.ui.fragment.DriverPingTaiFragment;
import com.revenant.driver.ui.fragment.DriverZhiPaiFragment;
import com.revenant.driver.utils.Constants;
import com.revenant.driver.utils.GsonUtil;
import com.revenant.driver.utils.LocatinNoDataService;
import com.revenant.driver.utils.LocationService;
import com.revenant.driver.utils.SPUtils;
import com.revenant.driver.utils.TokenHeadeInterceptor;
import com.revenant.driver.utils.Utils;
import com.revenant.driver.utils.apkUpdate.VersionUtils;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import constant.UiType;
import listener.OnBtnClickListener;
import model.UiConfig;
import model.UpdateConfig;
import update.UpdateAppUtils;

import static com.revenant.driver.bean.BaseBean.MyEventCode.LianWangPush;
import static com.revenant.driver.bean.BaseBean.MyEventCode.PingTaiPush;
import static com.revenant.driver.bean.BaseBean.MyEventCode.Xiao_Personal_Push_Code_NeWs;
import static com.revenant.driver.bean.BaseBean.MyEventCode.Xiao_Sys_Push_Code_NeWs;
import static com.revenant.driver.bean.BaseBean.MyEventCode.ZhiPai_Push_Code_NeWs;
import static com.revenant.driver.bean.Message.Driver_RenZheng_6;
import static com.revenant.driver.bean.Message.Driver_RenZheng_7;
import static com.revenant.driver.bean.Message.Driver_RenZheng_8;
import static com.revenant.driver.utils.Constants.Driver_GetDriverCar_info;
import static com.revenant.driver.utils.Constants.Driver_Location_Upload;
import static com.revenant.driver.utils.Constants.Get_personal_info;

public class DriverMainActivity extends BaseActivity {
    @BindView(R.id.left_base)
    ImageView leftBase;
    @BindView(R.id.right_base)
    ImageView rightBase;
    @BindView(R.id.basetitle_show_or_hide)
    LinearLayout basetitleShowOrHide;
    @BindView(R.id.tablayout)
    TabLayout tablayout;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.publishbotton)
    FloatingActionButton publishbotton;
    private Context context;
    private List<Fragment> fragmentList;
    private List<String> titleList;
    private NewMainAdapter newMainAdapter;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private AlertInfoListAdapter alertInfoListAdapter;
    private long exitTime = 0;

    private String apkUrl = "";
    private String updateTitle = "";
    private String updateContent = "";

    private int PushCodeStatus = 0;
    private int defaultselect = 0;

    private PopupWindow popstart;

    @Override
    public int getContentViewResId() {
        return R.layout.activity_driver_main;
    }

    @Override
    public void initView() {
        alertDialog();
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            defaultselect = extras.getInt("newsselect");
        }
        context = this;
        fragmentList = new ArrayList<>();
        titleList = new ArrayList<>();
        updateApks();
        if (SPUtils.getAccounId(context) != 0) {
            getpseronal();
            initupdate();

            TongJi(SPUtils.getUsermobile(context), DeviceUtils.getManufacturer() + "-" + DeviceUtils.getModel() + "-" + RomUtils.getRomInfo().getVersion(), AppUtils.getAppVersionName(), String.valueOf(SPUtils.getAccounId(context)), "0");
        }

//        startlocation();
//        if (SPUtils.getUserAuthentication(context).equals("1")) {
//            initLocation();
//            startLocation();
//        }
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        String rid = JPushInterface.getRegistrationID(getApplicationContext());
        if (SPUtils.getJpRidToken(getApplicationContext()).isEmpty()) {
            if (!rid.isEmpty()) {
                SPUtils.setJpRidToken(getApplicationContext(), rid);
            }
        }
    }

    @Override
    public void initData() {
        fragmentList.add(DriverPingTaiFragment.newInstance("DriverPingTai"));
        fragmentList.add(DriverZhiPaiFragment.newInstance("DriverZhiPai"));
        fragmentList.add(DriverLianWangFragment.newInstance("DriverLianWang"));

        titleList.add("平台");

        titleList.add("指派");

        titleList.add("联网");

        newMainAdapter = new NewMainAdapter(getSupportFragmentManager(), this, fragmentList, titleList);
//
        viewpager.setAdapter(newMainAdapter);
        tablayout.setupWithViewPager(viewpager);
        tablayout.getTabAt(defaultselect).select();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.d("重启:" + "onCreate:" + SPUtils.getPushCode(context));
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.left_base, R.id.right_base, R.id.publishbotton})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.left_base:
                if (SPUtils.getAccounId(context) == 0) {
                    startActivity(LoginActivity.class);
                } else {
                    startActivity(DriverMineActivity.class);
                }
                break;
            case R.id.right_base:
                if (SPUtils.getAccounId(context) == 0) {
                    startActivity(LoginActivity.class);
                } else {
                    startActivity(NewsActivity.class);
                }
                break;
            case R.id.publishbotton:
                if (SPUtils.getAccounId(context) == 0) {
                    startActivity(LoginActivity.class);
                } else {
                    App applicationContext = (App) getApplicationContext();
                    int userStatus = applicationContext.getUserStatus();
                    switch (userStatus) {
                        case 5:
                            startActivity(DriverPublishEmptyActivity.class);
                            break;
                        case 6:
                            showToast(Driver_RenZheng_6);
//                            startActivity(DriverRenZhengOneActivity.class);
                            startActivity(NewImproveDriverInfoaActivity.class);
                            break;
                        case 7:
                            showToast(Driver_RenZheng_7);
                            break;
                        case 8:
                            showToast(Driver_RenZheng_8);
//                            startActivity(DriverRenZhengOneActivity.class);
                            startActivity(NewImproveDriverInfoaActivity.class);
                            break;
                        default:
                    }
                }

                break;
        }
    }

    @Override
    protected boolean isshowtitlebar() {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyLocation();
        if (popstart != null) {
            popstart.dismiss();
        }
    }

    private void destroyLocation() {
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    private void initLocation() {
        locationClient = new AMapLocationClient(this);
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }

    private void startLocation() {
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    private void stopLocation() {
        // 停止定位
        locationClient.stopLocation();
    }

    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(1000 * 60 * 1 * 1);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        mOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.DEFAULT);//可选，设置逆地理信息的语言，默认值为默认语言（根据所在地区选择语言）
        return mOption;
    }

    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {

                StringBuffer sb = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if (location.getErrorCode() == 0) {
                    sb.append("定位成功" + "\n");
                    sb.append("定位类型: " + location.getLocationType() + "\n");
                    sb.append("经    度    : " + location.getLongitude() + "\n");
                    sb.append("纬    度    : " + location.getLatitude() + "\n");
                    sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
                    sb.append("提供者    : " + location.getProvider() + "\n");
                    SPUtils.setLongitude(context, String.valueOf(location.getLongitude()));
                    SPUtils.setLatitude(context, String.valueOf(location.getLatitude()));
                    initDataRecyclerview(String.valueOf(location.getLongitude()), String.valueOf(location.getLatitude()));

                    sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
                    sb.append("角    度    : " + location.getBearing() + "\n");
                    // 获取当前提供定位服务的卫星个数
                    sb.append("星    数    : " + location.getSatellites() + "\n");
                    sb.append("国    家    : " + location.getCountry() + "\n");
                    sb.append("省            : " + location.getProvince() + "\n");
                    sb.append("市            : " + location.getCity() + "\n");
                    sb.append("城市编码 : " + location.getCityCode() + "\n");
                    sb.append("区            : " + location.getDistrict() + "\n");
                    sb.append("区域 码   : " + location.getAdCode() + "\n");
                    sb.append("地    址    : " + location.getAddress() + "\n");
                    sb.append("兴趣点    : " + location.getPoiName() + "\n");

                    //定位完成的时间
                    sb.append("定位时间: " + Utils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
                } else {
                    //定位失败
                    sb.append("定位失败" + "\n");
                    sb.append("错误码:" + location.getErrorCode() + "\n");
                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
                    sb.append("错误描述:" + location.getLocationDetail() + "\n");
                }
                sb.append("***定位质量报告***").append("\n");
                sb.append("* WIFI开关：").append(location.getLocationQualityReport().isWifiAble() ? "开启" : "关闭").append("\n");
                sb.append("* GPS状态：").append(getGPSStatusString(location.getLocationQualityReport().getGPSStatus())).append("\n");
                sb.append("* GPS星数：").append(location.getLocationQualityReport().getGPSSatellites()).append("\n");
                sb.append("* 网络类型：" + location.getLocationQualityReport().getNetworkType()).append("\n");
                sb.append("* 网络耗时：" + location.getLocationQualityReport().getNetUseTime()).append("\n");
                sb.append("****************").append("\n");
                //定位之后的回调时间
                sb.append("回调时间: " + Utils.formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");

                //解析定位结果，
                String result = sb.toString();
//                tvResult.setText(result);
                LogUtils.d("定位数据是" + result);
            } else {
                LogUtils.d("定位失败，loc is null");
            }
        }
    };


    private String getGPSStatusString(int statusCode) {
        String str = "";
        switch (statusCode) {
            case AMapLocationQualityReport.GPS_STATUS_OK:
                str = "GPS状态正常";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPROVIDER:
                str = "手机中没有GPS Provider，无法进行GPS定位";
                break;
            case AMapLocationQualityReport.GPS_STATUS_OFF:
                str = "GPS关闭，建议开启GPS，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_MODE_SAVING:
                str = "选择的定位模式中不包含GPS定位，建议选择包含GPS定位的模式，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPERMISSION:
                str = "没有GPS定位权限，建议开启gps定位权限";
                break;
        }
        return str;
    }

    private void initDataRecyclerview(String lon, String lan) {
        PostRequest<String> post = OkGo.<String>post(Driver_GetDriverCar_info);
        post.params("userId", SPUtils.getAccounId(context));
        post.execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                DriverTrackBean listBean = GsonUtil.parseJsonWithGson(response.body(), DriverTrackBean.class);
                if (listBean.getCode().equals("0")) {
                    if (Integer.valueOf((Integer) listBean.getData())== 0) {
                        querensiconfirm(lon, lan);

                    }
                }

            }
        });
    }

    private void querensiconfirm(String lon, String lan) {
        OkGo.<String>post(Driver_Location_Upload)
                .params("x", lan)
                .params("y", lon)
                .params("userId", SPUtils.getAccounId(context))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DriverTrackBean queRenSiBean = GsonUtil.parseJsonWithGson(response.body(), DriverTrackBean.class);
                        if (queRenSiBean.getCode().equals("0")) {
                            LogUtils.d("位置上传");
                        }

                    }
                });
    }

    @Override
    public void onBackPressed() {

        System.out.println(System.currentTimeMillis());

        if (System.currentTimeMillis() - exitTime < 2000) {
            AppUtils.exitApp();
        } else {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_LONG).show();
            exitTime = System.currentTimeMillis();
        }

    }

    private void getpseronal() {

        OkGo.<String>get(Get_personal_info)
                .params("id", SPUtils.getAccounId(context))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.d("AAAA" + response.body());
                        try {
                            PersonalDetailBean g = GsonUtil.parseJsonWithGson(response.body(), PersonalDetailBean.class);
                            if (g.getCode().equals("0")) {
                                App applicationContext = (App) getApplicationContext();
                                if (g.getData().getStatus() != null) {
                                    applicationContext.setUserStatus(Integer.valueOf(g.getData().getStatus()));
                                    int userStatus = applicationContext.getUserStatus();
                                    switch (userStatus) {
                                        case 5:
                                            break;
                                        case 6:
                                            break;
                                        case 7:
                                            break;
                                        case 8:
                                            break;
                                        default:
                                    }

                                }


                            }
                        } catch (JsonSyntaxException ex) {
                            PersonalDetailBean g = GsonUtil.parseJsonWithGson(TokenHeadeInterceptor.decryptStr(response.body()), PersonalDetailBean.class);
                            if (g.getCode().equals("0")) {

                                App applicationContext = (App) getApplicationContext();
                                applicationContext.setUserStatus(Integer.valueOf(g.getData().getStatus()));
                                int userStatus = applicationContext.getUserStatus();
                                switch (userStatus) {
                                    case 5:
//                                    initLocation();
//                                    startLocation();

//                                        Intent intent = new Intent(DriverMainActivity.this, LocationService.class);
//                                        startService(intent);
                                        break;
                                    case 6:
                                        break;
                                    case 7:
                                        break;
                                    case 8:
                                        break;
                                    default:
                                }


                            }
                        }

                    }
                });
    }


    private void updateApks() {
        if (SPUtils.getUpdateNum(context) == 1) {
            OkGo.<String>get(Constants.Update_Apk_0825)
                    .params("appVersion", VersionUtils.getVersionCode())
                    .params("platform", "0")
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            UpdateBean updateBean = GsonUtil.parseJsonWithGson(response.body(), UpdateBean.class);
                            if (updateBean.getData() != null) {
                                Integer versioncode = Integer.valueOf(updateBean.getData().getVersion());
                                if (versioncode > VersionUtils.getVersionCode()) {
                                    updateTitle = updateBean.getData().getTitle();
                                    updateContent = updateBean.getData().getContent();
                                    apkUrl = updateBean.getData().getUrl();
                                    boolean isAuto = updateBean.getData().isIsAuto();

                                    if (updateBean.getData().getAutoVersion()!=null){
                                        Integer integer = Integer.valueOf(updateBean.getData().getAutoVersion());
                                        if (VersionUtils.getVersionCode()<integer){
                                            isAuto=true;
                                        }
                                    }


                                    String name = "driver";
                                    File filePictures = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
                                    String absolutePath1 = filePictures.getAbsolutePath();
                                    String androidQpath = absolutePath1 + "/" + name;

                                    UpdateConfig updateConfig = new UpdateConfig();
                                    updateConfig.setCheckWifi(false);
                                    updateConfig.setNeedCheckMd5(false);
                                    updateConfig.setShowNotification(true);
                                    updateConfig.setShowDownloadingToast(true);
                                    updateConfig.setAlwaysShowDownLoadDialog(true);
                                    updateConfig.setApkSaveName(name);
                                    updateConfig.setApkSavePath(androidQpath);
                                    updateConfig.setNotifyImgRes(R.mipmap.icon);
                                    updateConfig.setForce(isAuto);
                                    final UiConfig uiConfig = new UiConfig();
                                    uiConfig.setUiType(UiType.PLENTIFUL);
                                    uiConfig.setCancelBtnText("下次再说");
                                    uiConfig.setUpdateBtnText("立即升级");

                                    UpdateAppUtils
                                            .getInstance()
                                            .apkUrl(apkUrl)
                                            .updateTitle(updateTitle)
                                            .updateContent(updateContent)
                                            .uiConfig(uiConfig)
                                            .updateConfig(updateConfig)
                                            .setUpdateBtnClickListener(new OnBtnClickListener() {
                                                @Override
                                                public boolean onClick() {
                                                    return false;
                                                }
                                            })
                                            .setCancelBtnClickListener(new OnBtnClickListener() {
                                                @Override
                                                public boolean onClick() {
                                                    return false;

                                                }
                                            })
                                            .update();
                                }

                            }
                        }


                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            String msgerror = response.getException().getMessage();
                            showLongToast(msgerror);
                        }

                        @Override
                        public void onFinish() {
                            super.onFinish();
                        }
                    });
        }
        SPUtils.setUpdateNum(context, 2);
    }



    @Override
    protected void onRestart() {
        super.onRestart();

        LogUtils.d("重启:" + "onRestart():" + SPUtils.getPushCode(context));

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (SPUtils.getAccounId(context) != 0) {
            getpseronal();
            initupdate();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        LogUtils.d("重启:" + "onStop:" + SPUtils.getPushCode(context));


    }

    private void jumpPush(Class<?> clz) {
        startActivity(clz);
        SPUtils.setPushCode(context, 0);
    }

    private void jumpPush(Class<?> clz, Bundle bundle) {
        startActivity(clz, bundle);
        SPUtils.setPushCode(context, 0);
    }


    private void initupdate() {
        // TODO: 2020/6/29  
        OkGo.<String>post(Driver_GetDriverCar_info)
                .params("userId", SPUtils.getAccounId(App.getApplication()))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.code()==200){
                            try {
                                DriverTrackBean listBean = GsonUtil.parseJsonWithGson(response.body(), DriverTrackBean.class);
                                if (listBean.getCode().equals("0")) {
                                    if (Integer.valueOf((Integer) listBean.getData()) == 0) {


                                        if (LocationService.getLastLocation() == null) {
                                            Intent intent = new Intent(DriverMainActivity.this, LocationService.class);
                                            startService(intent);
                                        }




                                    } else {

                                        if (LocatinNoDataService.getLastLocation() == null) {
                                            Intent intent = new Intent(DriverMainActivity.this, LocatinNoDataService.class);
                                            startService(intent);
                                        }



                                    }
                                } else {
                                    if (LocatinNoDataService.getLastLocation() == null) {
                                        Intent intent = new Intent(DriverMainActivity.this, LocatinNoDataService.class);
                                        startService(intent);
                                    }
                                }
                            } catch (IllegalStateException e) {

                            } catch (JsonSyntaxException e) {

                            }
                        }


                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (LocatinNoDataService.getLastLocation() == null) {
                            Intent intent = new Intent(DriverMainActivity.this, LocatinNoDataService.class);
                            startService(intent);
                        }

                    }
                });
    }

//    @Override
//    protected void protectApp() {
//        startActivity(new Intent(this, SplashActivity.class));
//        finish();
//    }

    private void startlocation() {
        Intent serviceIntend = new Intent(context, LocatinNoDataService.class);
        startService(serviceIntend);

    }

    private void TongJi(String mobile, String mobileVersion, String appVersion, String accountId, String role) {
        Map<String, String> map = new HashMap<>();
        map.put("mobile", mobile);
        map.put("mobileVersion", mobileVersion);
        map.put("appVersion", appVersion);
        map.put("accountId", accountId);
        map.put("role", role);
        JSONObject jsonObject = new JSONObject(map);
        OkGo.<String>post(Constants.TongJi_Login)
                .upJson(jsonObject)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
//                        TongJiListBean tongjiList = GsonUtil.parseJsonWithGson(response.body(), TongJiListBean.class);
//                        if (tongjiList.getData() != null) {
//                            if (tongjiList.getData().size() > 0) {
//                                darkenBackground(0.3f);
//                                alertInfoListAdapter.setNewData(tongjiList.getData());
//                                popstart.showAtLocation(tablayout, Gravity.CENTER, 0, 0);
//                            }

//                        } else {
//
//                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });
    }


    private void alertDialog() {
        alertInfoListAdapter = new AlertInfoListAdapter();
        View contentView = View.inflate(this, R.layout.alertxieyilogin, null);
        ImageView imageclose = (ImageView) contentView.findViewById(R.id.right_close);
        RecyclerView xieyirecyclerew = (RecyclerView) contentView.findViewById(R.id.xieyirecyclew);
        xieyirecyclerew.setLayoutManager(new LinearLayoutManager(this));
        xieyirecyclerew.setAdapter(alertInfoListAdapter);
        alertInfoListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                popstart.dismiss();
                Bundle bundle = new Bundle();
                bundle.putString("weburl", alertInfoListAdapter.getData().get(position).getUrl());
                bundle.putString("conorderId", String.valueOf(alertInfoListAdapter.getData().get(position).getOrderId()));
                startActivity(XieYiActivity.class, bundle);

            }
        });
        popstart = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true
        );

        imageclose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popstart.dismiss();
            }
        });
        popstart.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        // 设置PopupWindow是否能响应外部点击事件
        popstart.setOutsideTouchable(false);
        // 设置PopupWindow是否能响应点击事件
        popstart.setTouchable(true);
        popstart.setContentView(contentView);

        popstart.setAnimationStyle(R.style.Popupwindow);

        popstart.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                darkenBackground(1f);
            }
        });


    }

    private void darkenBackground(Float alpha) {
        if (alpha < 0 || alpha > 1) {
            return;
        }
        WindowManager.LayoutParams windowLP = getWindow().getAttributes();
        windowLP.alpha = alpha;
        if (alpha == 1) {
            //不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        } else {
            //此行代码主要是解决在华为手机上半透明效果无效的bug
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        }
        getWindow().setAttributes(windowLP);

    }


}
